package listener;
import jdbc.JdbcUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@WebListener
public class ApplicationContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        try {
            System.setOut(new PrintStream(System.out,true,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("Servlet上下文初始化");

        ServletContext Context = sce.getServletContext();
        String jdbcConfig = Context.getInitParameter("jdbcConfig");
        if (jdbcConfig != null && !"".equals(jdbcConfig)) {
            InputStream is = this.getClass().getResourceAsStream(jdbcConfig);
            Properties prop = new Properties();
            try {
                prop.load(is);
    //            对数据源运行初始化操作
                JdbcUtil.initDataSource(prop);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Servlet上下文销毁");
        JdbcUtil.destroyDataSource();
    }

}
